package com.fingerth.crawler.base

import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.fingerth.crawler.R
import com.fingerth.crawler.utils.permission.PermissionUtils
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.ParameterizedType
import kotlin.coroutines.CoroutineContext

abstract class BaseAct<T : ViewBinding>(private val e: Boolean = false) : AppCompatActivity(), CoroutineScope {
    private var _binding: T? = null
    val vBinding: T get() = _binding!!

    //请求权限工具类,用的时候才初始化
    val permissionUtils: PermissionUtils by lazy { PermissionUtils() }

    private val job: Job by lazy { Job() }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job // Activity的协程


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            (javaClass.genericSuperclass as? ParameterizedType)?.let { _binding = (it.actualTypeArguments[0] as Class<*>).getMethod("inflate", LayoutInflater::class.java).invoke(null, layoutInflater) as T }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        if (_binding != null) {
            setContentView(vBinding.root)
            immersionBar {
                navigationBarColor(R.color.white)
                statusBarDarkFont(true)
            }
            //lifecycle.addObserver(SimpleLifecycleListener(this))
            initStatusBar()
            initView()
            if (e) eventBusRegister()
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            when (requestCode) {
                PermissionUtils.CODE_PERMISSION_ALL -> {
                }
                PermissionUtils.CODE_PERMISSION_WRITE_EXTERNAL_STORAGE -> {
                    permissionUtils.showOpenPermissionsDialog(this, msg = "已拒绝读写文件夹权限,要使用相关功能,请您打开权限.\r\n选择权限管理-读写手机存储")
                }
                PermissionUtils.CODE_PERMISSION_CAMERA -> {
                }
                PermissionUtils.CODE_PERMISSION_ACCESS_FINE_LOCATION -> {
                }
            }
        } else {
            //授权成功之后
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        job.cancel() // 关闭页面后，结束所有协程任务
        if (e) eventBusUnregister()
    }


    //    abstract fun viewBinding(): T
    abstract fun initStatusBar()
    abstract fun initView()
    open fun eventBusRegister() = EventBus.getDefault().register(this)
    open fun eventBusUnregister() = EventBus.getDefault().unregister(this)


}